<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/29 0029
 * Time: 下午 7:18
 */
namespace app\api\service;

use app\admin\model\Memberrule;
use app\admin\model\Membertype;
use app\common\BaseHelper;
use app\common\model\User;
use app\common\model\Useraccountdetails;
use app\common\model\Usermemberhistory;
use app\lib\exception\ParameterException;
use think\Exception;


class Member{
    private $memberId;
    private $memRuleId;
    private $uid;

    function __construct($id)
    {
        $this->memberId = $id;
        $this->uid = Token::getCurrentUid();
    }

    public function open(){
        $member = Membertype::get($this->memberId);
        try{
            if(!$member){
                throw new ParameterException([
                    'msg' => '该会员卡不存在'
                ]);
            }
            if($member->status == 0 || $member->status == 2){
                throw new ParameterException([
                    'msg' => '商家没有启用该会员卡'
                ]);
            }
        }catch (Exception $ex){
            return show(config('status.ERROR_STATUS'),$ex->msg,$ex->msg);
        }

        $memberrule = Memberrule::get($member->memRuleId);
        $this->memRuleId = $member->memRuleId;

        $openCondition = $member->openCondition;
        if($openCondition==1){
            //充值开通
            $memRule = Memberrule::get($this->memRuleId);
            $money = $memRule->rechargeOpenMoney;
            //充值返还
            $returnMoney = 0;
            if($memRule->returnMoney){
                $returnMoney = $memRule->returnMoney;
            }
            $rechargeIntegral = 0;
            if($memRule->rechargeIntegral){
                $rechargeIntegral = $memRule->rechargeIntegral;
            }
            $data = [
                'money' => $money,
                'returnMoney' => $returnMoney,
                'rechargeIntegral' => $rechargeIntegral,
                'tenantId' => $member->tenantId
            ];
            //创建会员开通订单
            $status = $this->createMemberOrder($data);
            if($status['pass']){
                $UserRecharge = new UserRecharge();
                return $UserRecharge->Recharge($status['id'],$status['type']);
            }

        }else{
            //无条件开通
            $user = User::get($this->uid);
            $user->typeId = $member->id;
            $user->memType = $member->memType;
            $user->isMember = 2;
            if($member->endTime != 0){
                $user->memberendtime = time() + $member->endTime;
            }else{
                $user->memberendtime = 0;
            }

            $returndata = [
                'isfree' => 0,
                'data' => '免费开通会员成功'
            ];
            if($user->save()){
                $this->inssertHistoryMemberRule($user->id,$member,$memberrule);
                return show(config('status.SUCCESS_STATUS'),'免费开通会员成功',$returndata);
            }else{
                return show(config('status.ERROR_STATUS'),'开通会员失败','开通会员失败');
            }


        }
    }

    private function createMemberOrder($data){
        $Useraccountdetails = new Useraccountdetails();
        $id = BaseHelper::getUUID();
        $Useraccountdetails->id = $id;
        $Useraccountdetails->userId = $this->uid;
        $Useraccountdetails->orderNO = Order::makeOrderNo();
        $Useraccountdetails->record_type = $Useraccountdetails::TYPE_3;
        $Useraccountdetails->memberId = $this->memberId;
        $Useraccountdetails->money = $data['money'];
        $Useraccountdetails->returnMoney = $data['returnMoney'];
        $Useraccountdetails->rechargeIntegral = $data['rechargeIntegral'];
        $Useraccountdetails->rechargeStatus = 0;
        $Useraccountdetails->tenantId = $data['tenantId'];
        if($Useraccountdetails->save()){
            return [
                'id' => $id,
                'type' =>$Useraccountdetails->record_type,
                'pass' => true
            ];
        }else{
           return [
               'pass' => false
           ];
        }

    }

    /**
     * 为当前用户开通的会员卡绑定历史规则（避免会员卡修改）
     * @param $userId
     * @param $membertype
     * @param $memberrule
     */
    private function inssertHistoryMemberRule($userId,$membertype,$memberrule){
        $Usermemberhistory = new Usermemberhistory();
        $history = $Usermemberhistory->where('userId',$userId)->find();
        if($history){
            $history->memType = $membertype->memType;
            $history->openCondition = $memberrule->openStatus;
            $history->endTime = $membertype->endTime;
            $history->term = $membertype->term;
            $history->timetype = $membertype->timetype;
            $history->tenantId = $membertype->tenantId;
            $history->rechargeOpenMoney = $memberrule->rechargeOpenMoney;
            $history->returnMoney = $memberrule->returnMoney;
            $history->rechargeIntegral = $memberrule->rechargeIntegral;
            $history->isMemBerShop = $memberrule->isMemBerShop;
            $history->memberDiscounts = $memberrule->memberDiscounts;
            $history->consumeMoney = $memberrule->consumeMoney;
            $history->consumeIntegral = $memberrule->consumeIntegral;
            $history->save();
        }else{
            $Usermemberhistory->id = BaseHelper::getUUID();
            $Usermemberhistory->userId = $userId;
            $Usermemberhistory->membertype_id = $membertype->id;
            $Usermemberhistory->memType = $membertype->memType;
            $Usermemberhistory->openCondition = $memberrule->openStatus;
            $Usermemberhistory->endTime = $membertype->endTime;
            $Usermemberhistory->term = $membertype->term;
            $Usermemberhistory->timetype = $membertype->timetype;
            $Usermemberhistory->tenantId = $membertype->tenantId;
            $Usermemberhistory->rechargeOpenMoney = $memberrule->rechargeOpenMoney;
            $Usermemberhistory->returnMoney = $memberrule->returnMoney;
            $Usermemberhistory->rechargeIntegral = $memberrule->rechargeIntegral;
            $Usermemberhistory->isMemBerShop = $memberrule->isMemBerShop;
            $Usermemberhistory->memberDiscounts = $memberrule->memberDiscounts;
            $Usermemberhistory->consumeMoney = $memberrule->consumeMoney;
            $Usermemberhistory->consumeIntegral = $memberrule->consumeIntegral;
            $Usermemberhistory->save();
        }


    }
}